package customerEnter.Frame.conntroller;

import static com.google.common.collect.Maps.newHashMap;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.portlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import customerEnter.Frame.Utils.DateUtils;
import customerEnter.Frame.Utils.Log4j;
import customerEnter.Frame.Utils.UrlEncryptionUtils;
import customerEnter.Frame.bean.DMLSuccessOrFailure;
import customerEnter.Frame.conntroller.tool.ErrorMessageInfo;
import customerEnter.tool.WhetherToEmpty;

/**
 * 
 * 
 * 类名称：BaseConntrollerFrame 类描述： 创建人：dy 创建时间：2016-7-22 上午10:51:35
 * 
 */
public class BaseConntrollerFrame {

	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;

	@SuppressWarnings("rawtypes")
	protected List<?> ConntroList = new ArrayList();

	protected Map<String, List<?>> ConntroJsonMap = new HashMap<String, List<?>>();

	protected Map<String, Object> ConntroJsonObject = new HashMap<String, Object>();

	protected BaseConntrollerFrameConntroView ConntroView;

	protected ConntrollerFrameModel frameModel;
	protected String _term;

	protected ModelAndView modelAndView = new ModelAndView();

	@ModelAttribute
	public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
		SetRequestHeader(request, response);
	}

	private void SetRequestHeader(HttpServletRequest request, HttpServletResponse response) {

		this.request = request;
		this.response = response;

		response.setHeader("Access-Control-Allow-Origin", "*"); // 解决跨域访问报错
		response.setHeader("Access-Control-Allow-Methods", "*");
		response.setHeader("Access-Control-Max-Age", "3600"); // 设置过期时间
		response.setHeader("Access-Control-Allow-Headers",
				"Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
		response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP
		response.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0.
													// response.setHeader("Expires",
													// "0");
		this.session = request.getSession();
		ConntroView = new BaseConntrollerFrameConntroView(request, response);
		frameModel = new ConntrollerFrameModel(ConntroView, ConntroJsonObject);
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			response.setHeader("contentType", "text/html; charset=utf-8");
		} catch (UnsupportedEncodingException e) {
			Log4j.setLog4j(this.getClass());
			Log4j.Log4JOutError("設置編碼失敗");
		}
	}

	/**
	 * 數據集合 map 的key 一定要是string 否則可能出現異常 單獨輸出一個java bean 是不行的
	 * 必須使用集合包裝一下(因為框架沒有依賴model項目 json解析的時候找不到單個的bean 的結構)
	 */
	public void sendOutPrint() {
		try {
			PrintWriter out = response.getWriter();
			StringBuffer string = new StringBuffer();
			for (Entry<String, List<?>> entry : ConntroJsonMap.entrySet()) {
				ConntroJsonObject.put(entry.getKey(), entry.getValue());
			}
			try {
				// JSONObject jsonObject =
				// JSONObject.fromObject(ConntroJsonObject);
				String jsonObjects = JSON.toJSONString(ConntroJsonObject);
				// String jsonObjects = jsonObject.toString();
				String easybuyCallback = request.getParameter("icyCallback");
				if (WhetherToEmpty.StringWhetherToEmpty(easybuyCallback)) {
					string.append(jsonObjects);
				} else {
					string.append(easybuyCallback + "(" + jsonObjects + ")");
				}
			} catch (Exception e) {
				Log4j.Log4JOutError(e.getMessage());
			}
			float in = string.toString().getBytes().length;
			Log4j.setLog4j(getClass());
			Log4j.Log4jOutInfo(in / 1024 + "K" + "  " + in / 1024 / 1024 + "M");
			out.print(string);
			out.flush();
			out.close();
			ConntroJsonMap.clear();
			ConntroList.clear();
		} catch (IOException e) {
			Log4j.Log4JOutError(e.getMessage());
		}
	}

	public boolean IfName(Object object) {
		String nameString = object.getClass().getSuperclass().getName();
		String[] strings = new String[] { "java.util.AbstractMap", "java.util.AbstractList" };
		boolean bool = false;
		for (String string : strings) {
			if (string.equals(nameString)) {
				bool = true;
				break;
			}
		}
		return bool;
	}

	public Map<String, List<?>> getConntroJsonMap() {
		return ConntroJsonMap;
	}

	public Map<String, Object> getConntroJsonObject() {
		return ConntroJsonObject;
	}

	public void DMLDeleteOrUpdateOrAdd(boolean bool, DMLSuccessOrFailure SuccessInfo, DMLSuccessOrFailure Failure) {
		if (bool) {
			if (!WhetherToEmpty.ObjectWhetherToEmpty(SuccessInfo.getType())) {
				frameModel.SetSuccessInfo(SuccessInfo.getUrl(), SuccessInfo.getType());
			} else {
				frameModel.SetSuccessInfo(SuccessInfo.getUrl());
			}
		} else {
			if (!WhetherToEmpty.ObjectWhetherToEmpty(Failure.getType())) {
				frameModel.SetFailure(Failure.getUrl(), Failure.getType());
			} else {
				frameModel.SetFailure(Failure.getUrl());
			}
		}
	}

	public void sendAsEncryptionError() {
		Log4j.Log4JOutError(" parame_Error");
		ConntroJsonObject.put("info", "parame_Error");
	}

	public void sendAsTimeError() {
		Log4j.Log4JOutError(" time_Error");
		ConntroJsonObject.put("info", "time_Error");
	}

	public boolean AsEncryption() {
		String _encryption = request.getParameter("_encryption");
		if (!WhetherToEmpty.StringWhetherToEmpty(_encryption)) {
			if (encryption(_encryption)) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}

	public Long _termTime() {
		_term = request.getParameter("_term");
		long lo = 0;
		if (!WhetherToEmpty.StringWhetherToEmpty(_term)) {
			Long _termInt = Long.parseLong(_term);
			Long _nowTime = DateUtils.dateToUnixTimestamp();
			System.out.println("獲取的時間:" + _termInt);
			System.out.println("當前的時間:" + _nowTime);
			lo = _nowTime - _termInt;
		}
		return lo;
	}

	/**
	 * 地址解密
	 */
	@SuppressWarnings("unchecked")
	private boolean encryption(String _encryption) {
		String url = request.getRequestURL().toString();
		String pram = "";
		Enumeration<String> names = request.getParameterNames();

		while (names.hasMoreElements()) {
			String str = names.nextElement();
			if (!"_encryption".equals(str) && !"_term".equals(str) && !"_".equals(str)
					&& !"easybuyCallback".equals(str)) {
				pram += str + "=" + request.getParameter(str);
			}
		}
		url += pram;

		for (int i = 0, k = 97; i < 10 && k < 107; i++, k++) {
			char ch = (char) k;
			url = url.replace("" + i + "", "" + ch);
		}
		url = UrlEncryptionUtils.exChange(url);
		url = url.replace(" ", "");
		System.out.println(url);
		int[] in = UrlEncryptionUtils.string2ASCII(url);
		String ass = "";
		int K = 0;
		for (int i : in) {
			ass += i + K;
			K++;
		}
		System.out.println("獲取到的：" + _encryption);
		System.out.println("解析出來的：" + ass);
		return ass.equals(_encryption);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map<String, String[]> setPamar(List<String> list) {

		Map<String, Object> li = request.getParameterMap();
		Map<String, String[]> map = newHashMap();
		Map<String, String> pas = newHashMap();
		for (String string2 : list) {
			pas.put(string2, string2);
		}
		for (Entry<String, Object> entry : li.entrySet()) {
			String key = entry.getKey();
			String[] strings = request.getParameterValues(key);
			String stPas = pas.get(key);
			if (!WhetherToEmpty.StringWhetherToEmpty(stPas) && stPas.length() > 0) {
				int i = 0;
				for (String string1 : strings) {
					strings[i] = UrlEncryptionUtils.IcyDecrypt(string1);
					// System.out.println(key + ":" + strings[i]);
					i++;
				}
			}
			map.put(key, strings);
		}
		HashMap m = new HashMap(request.getParameterMap());
		for (Entry<String, String[]> entry : map.entrySet()) {
			m.put(entry.getKey(), entry.getValue());
		}

		HttpServletRequest req = (HttpServletRequest) request;
		ParameterRequestWrapper wrapRequest = new ParameterRequestWrapper(req, m);
		request = wrapRequest;
		return map;
	}

	public void resultInfoERROR(ErrorMessageInfo errorCode) {
		ConntroJsonObject.put("result", "false");
		ConntroJsonObject.put("error", errorCode.getMessage());
		ConntroJsonObject.put("code", errorCode.getCode());
	}

	public void resultInfoSUCCESS() {
		ConntroJsonObject.put("result", "true");
	}

	public ModelAndView toPath(String url) {
		modelAndView.setViewName(url);
		return modelAndView;
	}

	public void addRequestModel(String name, Object obj) {
		modelAndView.addObject(name, obj);
	}

	public void addRequestPage(String name, Object obj) {
		request.setAttribute(name, obj);
	}

	public static void main(String[] args) throws Throwable {
		// ClassPool cp = ClassPool.getDefault();
		// CtClass cc = cp.get("controller.FrameQueryTest");// 獲取類
		// System.out.println(cc.getName());
		// outMethods2("javassist.Hello");
	}

}
